# -*- coding: utf-8 -*-
"""
@Time ： 2025/6/3 15:04
@Auth ： 九问
@File ：ddt_utils.py
@IDE ：PyCharm
@Email : 2750826557@qq.com
"""
import yaml
import copy
import logging

logger = logging.getLogger("ddt")


def read_testcase(yaml_path):
    logger.info(f"开始读取测试用例文件: {yaml_path}")

    try:
        with open(yaml_path, encoding="utf-8") as f:
            case_li = yaml.safe_load(f)

            if not case_li:
                logger.warning("测试用例文件为空")
                return []

            logger.debug(f"原始用例数据: {case_li}")

            if len(case_li) >= 2:
                logger.info("识别为流程用例")
                logger.debug(f"流程用例包含 {len(case_li)} 个步骤")
                return [case_li]

            elif "parametrize" in case_li[0]:
                logger.info("识别为数据驱动用例")
                base_case = case_li[0]

                # 记录参数化信息
                logger.debug(f"基础用例: {base_case}")
                logger.info(f"参数名称: {base_case['parametrize'][0]}")
                logger.info(f"参数值组数: {len(base_case['parametrize']) - 1}")

                param_names = base_case["parametrize"][0]
                param_values = base_case["parametrize"][1:]

                generated_cases = []
                for i, values in enumerate(param_values, 1):
                    logger.debug(f"正在处理第 {i} 组参数: {values}")

                    new_case = copy.deepcopy(base_case)
                    del new_case["parametrize"]
                    logger.debug("已创建用例副本并移除parametrize字段")

                    # 自动填充请求数据
                    if "request" not in new_case:
                        new_case["request"] = {}
                        logger.debug("添加request字段")

                    method = new_case["request"].get("method", "get").lower()
                    logger.info(f"请求方法: {method}")

                    if method in ["post", "put", "patch"]:
                        if "json" not in new_case["request"]:
                            new_case["request"]["json"] = {}
                        for name, value in zip(param_names, values):
                            new_case["request"]["json"][name] = value
                        logger.debug(f"设置JSON参数: {new_case['request']['json']}")
                    else:
                        if "params" not in new_case["request"]:
                            new_case["request"]["params"] = {}
                        for name, value in zip(param_names, values):
                            new_case["request"]["params"][name] = value
                        logger.debug(f"设置URL参数: {new_case['request']['params']}")

                    generated_cases.append(new_case)
                    logger.debug(f"第 {i} 个用例生成完成")

                logger.info(f"成功生成 {len(generated_cases)} 个数据驱动用例")
                return generated_cases

            else:
                logger.info("识别为单接口用例")
                return case_li

    except yaml.YAMLError as e:
        logger.error(f"YAML解析错误: {str(e)}")
        return []
    except Exception as e:
        logger.error(f"处理测试用例时发生错误: {str(e)}", exc_info=True)
        return []
